﻿namespace EFS.RC.CC.Messages
{
	public abstract class Message : EFS.Common.Serialization.ISerializable
	{
		/// the content type template
		public const System.String contentType = "application/EFS.RC.CC.Messages.Message+xml";

		/// Property ContentType: Get
		public static System.String ContentType
		{
			get
			{
				return contentType;
			}
		}

		/// Serialize
		public abstract void Serialize(EFS.Common.Serialization.XmlWriter xmlWriter);

		/// Deserialize
		public abstract void Deserialize(EFS.Common.Serialization.XmlReader xmlReader);

		/// <summary>
		/// Load from XML
		/// </summary>
		/// <param name="messageXml"></param>
		/// <returns></returns>
		public static System.String Serialize(Message message)
		{
			// make sr
			EFS.Common.Serialization.XmlWriter xmlWritter = new EFS.Common.Serialization.XmlWriter();

			try
			{
				// write    
				xmlWritter.WritePolymorphic("EFS.RC.CC.Messages.Message", message);
			}
			catch (System.Exception ex)
			{
				// throw
				throw new System.Exception(System.String.Format("Failed to serialize EFS.RC.CC.Messages.Message"), ex);
			}
			finally
			{
				// cose stream
				xmlWritter.Close();
			}

			// done
			return xmlWritter.Text;
		}

		/// <summary>
		/// Serialize to byte array
		/// </summary>
		/// <param name="message"></param>
		/// <returns></returns>
		public static System.Byte[] SerializeToByteArray(Message message)
		{
			try
			{
				// get string serialized
				System.String serStr = Serialize(message);

				// get bytes
				System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
				return encoding.GetBytes(serStr);
			}
			catch (System.Exception ex)
			{
				// throw
				throw
					new System.Exception(
						System.String.Format("Failed to serialize message type = {0}", message.GetType()),
						ex);
			}
		}

		/// <summary>
		/// Load from XML
		/// </summary>
		/// <param name="messageXml"></param>
		/// <returns></returns>
		public static Message Deserialize(System.String messageXml)
		{
			// make sr
			EFS.Common.Serialization.XmlReader xmlReader = new EFS.Common.Serialization.XmlReader(messageXml);

			// form meta
			Message retValue = null;
			try
			{
				retValue = xmlReader.ReadPolymorphic("EFS.RC.CC.Messages.Message") as Message;
			}
			catch (System.Exception ex)
			{
				// set to null
				retValue = null;

				// throw
				throw new System.Exception(System.String.Format("Failed to deserialize EFS.RC.CC.Messages.Message {0}", messageXml), ex);
			}
			finally
			{
				// cose stream
				xmlReader.Close();
			}

			// done
			return retValue;
		}
	}

}